package com.iwunu.auth.util;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.iwunu.auth.vo.JwtRole;

import java.util.ArrayList;
import java.util.List;

/**
 * jwt角色json工具类
 * @author vivi207
 *
 */
public class JwtRoleJsonUtils {
	private final static ObjectMapper objectMapper = new ObjectMapper();
	static {
		objectMapper.setSerializationInclusion(Include.NON_NULL);  
	}
	private final static JavaType javaType = getCollectionType(ArrayList.class, JwtRole.class);

	public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
		return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
	}
	
	/**
	 * 解析
	 * @param jsonString
	 * @return
	 */
	public static List<JwtRole> parse(String jsonString){
		if(jsonString==null || "".equals(jsonString)) {
			return null;
		}
		List<JwtRole> roles = null;
		try {
			roles = (List<JwtRole>)objectMapper.readValue(jsonString, javaType);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		} 
		return roles;
	}
	
	/**
	 * 格式化
	 * @param obj
	 * @return
	 */
	public static String format(Object obj) {
		if(obj==null || "".equals(obj)) {
			return null;
		}
		try {
			return objectMapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}
}
